define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Linkwx, GoPage, GoDialog,GoWapAuth) {
		$scope.data = new Object();
		$scope.isBind = false;
		$scope.isLoad = false;

		//画面加载
		$scope.$on('$ionicView.afterEnter', function() {
			$scope.init_data();
		}, false);

		$scope.init_data = function() {
			Linkwx.get_bindinfo({}, function(res) {
				if(!res.success) {
					GoDialog.toast(res.msg);
					return;
				}
				$scope.data = res.result || {};
				if($scope.data.mobile) {
					$scope.isLoad = true;
				}
				if($scope.data.verify_weixin) {
					$scope.isBind = true;
				}
			})
		}

		$scope.bind_thirdpart = function() {
			if(window.cordova && window.cordova.plugins) {
				//检查微信登录
				var scope = "snsapi_userinfo";
				var state = "_" + (+new Date());
				Wechat.auth(scope, state, function(response) {
					//接口登录
					var thirdid = response['code'];
					var thirdtype = "wx";

					Linkwx.thirdpart_bind({
						"id": thirdid,
						"type": thirdtype
					}, function(res) {
						if(!res.success) {
							GoDialog.toast(res.msg);
							return;
						}
						$scope.isBind = false;
						$scope.isLoad = false;
						$scope.init_data();
					})
				}, function(reason) {
					GoDialog.alert('提示', "失败: " + reason);
				});
			} else {
				GoWapAuth.bindWX();
			}
		}
		
		//解除绑定
		$scope.unbind_thirdpart = function() {
			var thirdtype = "wx";
			Linkwx.thirdpart_unbind({
				"type": thirdtype
			}, function(res) {
				if(!res.success) {
					GoDialog.toast(res.msg);
					return;
				}else{
					GoDialog.toast("解绑成功");
				}
				$scope.isBind = false;
				$scope.isLoad = false;
				$scope.init_data();
			})
		}

	}

	controller.$inject = ['$scope', 'Linkwx', 'GoPage', 'GoDialog','GoWapAuth'];

	return app.registerController("linkwxctrl", controller);
});